/**
 * 拓展String的endWith方法
 */
String.prototype.endWith = function(s){
	  if(s==null || s=="" || this.length==0 || s.length > this.length){
		  return false;
	  }
	  if(this.substring(this.length - s.length) == s){
		  return true;
	  }else{
		  return false;
	  }
	  return true;
}
/**
 * 拓展String的startWith方法
 */
String.prototype.startWith = function(s){
	  if(s==null || s=="" || this.length==0 || s.length>this.length){
		  return false;
	  }
	  if(this.substr(0,s.length)==s){
		  return true;
	  }else{
		  return false;
	  }
	  return true;
}
/**
 * 拓展array的contains方法
 */
Array.prototype.contains = function(item){
    for(i = 0; i < this.length; i++){
        if(this[i]==item){
        	return true;
        }
    }
    return false;
};
var commonUtil = {
		/**
		 * 得到请求的URL中的参数值
		 * @param name 参数名
		 * @returns
		 */
		getRequestParam : function(name){
			var url = decodeURI(window.location.search);
		    url = url.substr(1, url.length);
		    var paramArray = url.split("&");
		    for(var i = 0; i < paramArray.length; i++){
		    	var key = paramArray[i].split("=")[0];
		    	var value = paramArray[i].split("=")[1];
	 	    	if(key == name){
	 	    		return value;
	 	    	}
		    }
		    return ;
		},
		/**
		 * 获得UUID
		 * @returns
		 */
		getUUID : function(){
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
			        return v.toString(16);
			 });
		},
		/**
		 * 判断浏览器内核
		 */
		isTrident : function(){
			var u = navigator.userAgent;
			if(u.indexOf('Trident') > -1){
				return true;
			}else{
				return false;
			}
		},
		/**
		 * 验证是否是邮箱
		 */
		isEmail : function(str){
			var reg = new RegExp("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
			return reg.test(str);
		},
		/**
		 * 验证是否是邮箱
		 */
		isTel : function(str){
			var reg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;
			console.info(reg.test(str));
			return reg.test(str);
		},
		/**
		 * 
		 */
		isRegAccout : function(str){
			var reg = /^[0-9a-zA-Z]+$/;
			if(reg.test(str)){
				return true;
			}
			return false;
		},
		/**
		 * 验证一个字符串是否是空字符串
		 */
		isEmpty : function(str){
			if(str === null || str === undefined || $.trim(str) === ''){
				return true
			}
			return false;
		},
		
		isPdf : function(fileName){
			if(fileName.toLowerCase().endWith(".pdf")){
				return true;
			}
			return false;
		},
		isTxt : function(fileName){
			if(fileName.toLowerCase().endWith(".txt")){
				return true;
			}
			return false;
		},
		isWord : function(fileName){
			if(fileName.toLowerCase().endWith(".doc") || fileName.toLowerCase().endWith(".docx")){
				return true;
			}
			return false;
		},
		/**
		 * 让其调用者的线程等待，numberMillis 毫秒
		 */
		sleep : function(numberMillis){
			var now = new Date(); 
			var exitTime = now.getTime() + numberMillis; 
			while (true) { 
				now = new Date(); 
				if (now.getTime() > exitTime) 
				return;
			} 
		},
		/**
		 * 向浏览器增加cookie validTime < 0 时候,关闭浏览器则cookie失效
		 * 					  validTime为0 的时候。即可失效
		 * key：cookie的键
		 * value：cookie的值
		 * validTime：cookie的过期时间。以s为单位，例如过期时间一小时 validTime=3600
		 */
		addCookie : function(key, value, validTime){
			var cookieStr = key + "=" + value;
			if(!isNaN(validTime) && validTime > 0){
				var date = new Date();
				var ms = validTime * 1000;
				date.setTime(date.getTime() + ms);
				cookieStr += "; expires=" + date.toGMTString();
			}
			try{
				document.cookie = cookieStr;
			}catch (err) {
				console.info(err);
			}
			return true;
		},
		/**
		 * 读取cookie 参数 cookie的key
		 */
		readCookie : function(key){
			var arr,reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
			if(arr=document.cookie.match(reg))
			return unescape(arr[2]);
			else
			return null;
		},
		
		/**
		 * 设置input最大长度
		 */
		setMaxLength:function(n){
			$('input').attr('maxLength',n);
		},
		/**
		 * 获取域名 端口 项目名
		 */
		domain: function (){
		    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
		    var curWwwPath=window.document.location.href;
		    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
		    var pathName=window.document.location.pathname;
		    var pos=curWwwPath.indexOf(pathName);
		    //获取主机地址，如： http://localhost:8083
		    var localhostPaht=curWwwPath.substring(0,pos);
		    //获取带"/"的项目名，如：/uimcardprj
		    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
		   //  return projectName;
		    return window.location.protocol + "//" + window.location.host + projectName;
		},
		/**
		 * 获取域名
		 */
		hostName: function(){
			return window.location.protocol + "//" + window.location.host;
		}
}
/**
 * 自定义map集合
 * @returns
 */
var beskeMap = new Map(); 
function Map() {  
    this.arr = new Array();  
    var struct = function(key, value) {  
            this.key = key;  
            this.value = value;  
    };  
    this.put = function(key, value){  
          for (var i = 0; i < this.arr.length; i++) {  
              if ( this.arr[i].key === key ) {  
                     this.arr[i].value = value;  
                    return;  
               }  
          }  
       this.arr[this.arr.length] = new struct(key, value);  
    };  
    this.get = function(key) {  
       for (var i = 0; i < this.arr.length; i++) {  
          if ( this.arr[i].key === key ) {  
               return this.arr[i].value;  
            }  
        }  
      return null;  
     };  
     this.values=function(){  
        var value=[]  
       for (var i = 0; i < this.arr.length; i++) {  
          value.push(this.arr[i].value);  
       }  
       return value.join(",");  
     };  
     this.remove = function(key) {  
       var v;  
       for (var i = 0; i < this.arr.length; i++) {  
          v = this.arr.pop();  
          if ( v.key === key ) {  
           continue;  
       }  
       this.arr.unshift(v);  
      }  
     };  
     this.size = function() {  
    	 return this.arr.length;  
     };  
     this.isEmpty = function() {  
         return this.arr.length <= 0;  
     };
} 
var ajaxUtil = {
		/**
		 * ajax原始方法
		 */
		ajax : function(url, data, success, cache, async, type, dataType, error, traditional, processData, contentType){
			var type = type || 'post';// 默认请求类型
		    var dataType = dataType || 'json';// 默认接收数据类型
		    var async = async || false;// 默认异步请求
		    var cache = cache || false;// 默认不缓存 浏览器历史缓存
		    var success = success || function (data) {
		            alert("ajax请求成功");
		    };
		    var error = error || function (data) {
		    		alert("ajax请求失败");
		    };
		    var traditional = traditional || false;
		    $.ajax({
		        'url': url,
		        'data': data,
		        'type': type,
		        'dataType': dataType,
		        'traditional':traditional,
		        'processData':processData,
		        'contentType':contentType,
		        'async': async,
		        'success': success,
		        'error': error,
		        'jsonpCallback': 'jsonp' + (new Date()).valueOf().toString().substr(-4),
		        'beforeSend': function () {

		        },
		    });
		},
		/**
		 * ajax 提交表单（POST）
		 * formData : formData对象
		 */
		submitForm : function(formData, param, success, error){
			var url = param.url;
            var data = formData;
            var cache = param.cache || false;
			var async = param.async || false;
			var traditional = param.traditional || false;
			var processData = param.processData || false;
			var contentType = param.contentType || false;
			this.ajax(url, formData, success, cache, async, 'post','json', error, traditional, processData, contentType);
		},
		/**
		 * ajax get请求
		 */
		get : function(url, success, cache){
		    this.ajax(url, {}, success, cache, false, 'get','json');
		},
		/**
		 * ajax post请求
		 */
		post : function(param, success, error){
			var url = param.url;
			var data = param.data || null;
			var cache = param.cache || false;
			var async = param.async || false;
			var traditional = param.traditional || false;
			this.ajax(url, data, success, cache, async, 'post', 'json', error, traditional);
		},
		
		/**
		 * ajax jsonp跨域请求
		 */
		jsonp : function(url, success, cache){
			this.ajax(url, {}, success, cache, false, 'get','jsonp');
		}
}
var formUtil = {
		 setForm :function(obj,jsonValue) {
			    $.each(jsonValue, function (name, ival) {  
			        var $oinput = obj.find("input[name=" + name + "]"); 
			        if ($oinput.attr("type")== "radio" || $oinput.attr("type")== "checkbox"){  
			             $oinput.each(function(){  
			                 if(Object.prototype.toString.apply(ival) == '[object Array]'){// 是复选框，并且是数组
			                      for(var i=0;i<ival.length;i++){  
			                          if($(this).val()==ival[i])  
			                             $(this).attr("checked", "checked");  
			                      }  
			                 }else{  
			                     if($(this).val()==ival)  
			                        $(this).attr("checked", "checked");  
			                 }  
			             });  
			        }else if($oinput.attr("type")== "textarea"){// 多行文本框
			            obj.find("[name="+name+"]").html(ival);  
			        }else{  
			             obj.find("[name="+name+"]").val(ival);   
			        }  
			    });
		},
		/**
		 * 参数form jquery的form对象
		 */
		form2Json : function(form){
			var paramArray = form.serializeArray();
			var paramJson = {};
			for(var i = 0; i < paramArray.length; i++){
				paramJson[paramArray[i].name] = paramArray[i].value;
			}
			return paramJson;
		}
}
var selectUtil = {
	fillSelect : function(selectObj, dataList, valueName, textName){
		var childStr = "";
		for(var i = 0; i < dataList.length; i ++){
			var item = dataList[i];
			childStr = '"<option value="' + item[valueName] + '">' + item[textName] + '</option>"';
			selectObj.append($(childStr));
		}
	}
}
